package com.xm.zhEnHelper.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import com.xm.zhEnHelper.constant.PromptTemplate;
import com.xm.zhEnHelper.dto.ColumDTO;
import com.xm.zhEnHelper.dto.FieldValue;
import com.xm.zhEnHelper.service.TableOperateService;
import com.xm.zhEnHelper.service.Zh2EnService;
import com.xm.zhEnHelper.service.ZhToEnService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.messages.SystemMessage;
import org.springframework.ai.chat.model.ChatResponse;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.ai.ollama.OllamaChatModel;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

@Slf4j
@Service
@RequiredArgsConstructor
public class Zh2EnServiceImpl implements Zh2EnService {

    private final TableOperateService tableOperateService;

    private final ZhToEnService zhToEnService;

    private final OllamaChatModel ollamaChatModel;
    @Override
    public void zh2en(String schemaName, String tableName, String columnName) {


        List<List<FieldValue>> lists = tableOperateService.queryTableData(schemaName, tableName, List.of(columnName));
        for (List<FieldValue> list : lists) {
            FieldValue fieldValue = list.get(0);

            if (fieldValue.isTextType() && !fieldValue.isPrimaryKey()) {
                String chinese = StrUtil.toString(fieldValue.getFieldValue());
                if (StrUtil.isNotBlank(chinese)) {
                    if (zhToEnService.zhToEnExists(chinese)){
                        log.info("表:{}的列:{}的中文名称:{}已存在对应的英文名称，跳过转换", tableName, columnName, chinese);
                        continue;
                    }
                    String english = chinese2English(chinese);
                    if (StrUtil.isNotBlank(english)) {
                        zhToEnService.saveZhToEn(chinese, english);
                    } else {
                        log.warn("表:{}的列:{}的中文名称:{}转换为英文名称失败", tableName, columnName, chinese);
                    }
                }
            }

            if (fieldValue.isJsonType()){
                List<String> values = JSONUtil.toList(StrUtil.toString(fieldValue.getFieldValue()), String.class);
                if (CollUtil.isEmpty(values)) {
                    log.warn("表:{}的列:{}的json数据为空，跳过转换", tableName, columnName);
                    continue;
                }
                for (String value : values) {
                    if (StrUtil.isBlank(value)) {
                        log.warn("表:{}的列:{}的json数据:{}为空，跳过转换", tableName, columnName, value);
                        continue;
                    }
                    if (zhToEnService.zhToEnExists(value)){
                        log.info("表:{}的列:{}的json数据:{}已存在对应的英文名称，跳过转换", tableName, columnName, value);
                        continue;
                    }
                    String english = chinese2English(value);
                    if (StrUtil.isNotBlank(english)) {
                        zhToEnService.saveZhToEn(value, english);
                    } else {
                        log.warn("表:{}的列:{}的json数据:{}转换为英文名称失败", tableName, columnName, value);
                    }
                }
            }
        }

    }

    @Override
    public void updateColumnZhEn(String schemaName, String tableName, List<String> columnNames) {
        List<ColumDTO> columDTOS = tableOperateService.queryTableColumns(schemaName, tableName);
        // 找出表的主键
        ColumDTO primaryKeyColumn = columDTOS.stream().filter(ColumDTO::isPrimaryKey).findFirst().orElse(null);

        Assert.notNull(primaryKeyColumn, "表:" + tableName + "没有主键，请检查表结构");

        if (!columnNames.contains(primaryKeyColumn.getFieldName())){
            columnNames.add(primaryKeyColumn.getFieldName());
        }
        //查询出表中所有数据
        List<List<FieldValue>> dataList = tableOperateService.queryTableData(schemaName, tableName, columnNames);
        for (List<FieldValue> fieldValues : dataList) {
            Optional<FieldValue> primaryKeyFieldValueOptional = fieldValues.stream().filter(fieldValue -> StrUtil.equals(fieldValue.getFieldName(), primaryKeyColumn.getFieldName())).findFirst();
            if (primaryKeyFieldValueOptional.isEmpty()){
                throw new RuntimeException("表:" + tableName + "没有主键，请检查表结构");
            }
            FieldValue primaryKeyFieldValue = primaryKeyFieldValueOptional.get();
            for (FieldValue fieldValue : fieldValues) {
                if (columnNames.contains(fieldValue.getFieldName()) && !fieldValue.isPrimaryKey()){
                    List<String> fileValueEn = this.findFileValueEn(fieldValue);
                    if (CollUtil.isEmpty(fileValueEn)) {
                        log.warn("表:{}的列:{}的json数据为空，跳过转换", tableName, fieldValue.getFieldName());
                        continue;
                    }
                    if (fieldValue.isTextType()){
                        fieldValue.setFieldValue(fileValueEn.get(0));
                    }else if (fieldValue.isJsonType()){
                        fieldValue.setFieldValue(JSONUtil.toJsonStr(fileValueEn));
                    }else {
                        throw new RuntimeException("表:" + tableName + "的列:"+primaryKeyFieldValue.getFieldValue()+"的json数据:"+fieldValue.getFieldValue()+"转换为英文名称失败,{}");
                    }
                }
            }
            //更新表数据
            tableOperateService.updateTableData(schemaName, tableName, List.of(fieldValues));
        }
    }
    private List<String> findFileValueEn(FieldValue fieldValue){

        List<String> ens = new ArrayList<>();
        if (fieldValue.isTextType()) {
            String chinese = StrUtil.toString(fieldValue.getFieldValue());
            if (StrUtil.isNotBlank(chinese)) {
                String enText = zhToEnService.getEnText(chinese);
                if (StrUtil.isNotBlank(enText)){
                    ens.add(enText);
                }
            }
        }
        if (fieldValue.isJsonType()){
            List<String> values = JSONUtil.toList(StrUtil.toString(fieldValue.getFieldValue()), String.class);
            if (CollUtil.isEmpty(values)) {
                log.warn("json数据为空，跳过转换");
                return ens;
            }
            for (String value : values) {
                if (StrUtil.isBlank(value)) {
                    log.warn("json数据:{}为空，跳过转换", value);
                    continue;
                }
                String enText = zhToEnService.getEnText(value);
                if (StrUtil.isNotBlank(enText)){
                    ens.add(enText);
                }
            }
        }
        return ens;
    }

    private String  chinese2English(String chinese){
        if (StrUtil.isEmpty(chinese)){
            return chinese;
        }
        Prompt prompt = new Prompt(List.of(new SystemMessage(PromptTemplate.CHINESE_TO_ENGLISH_TEMPLATE),
                new SystemMessage("需要翻译的文字：\n ```text" + chinese +"\n```")));
        ChatResponse call = ollamaChatModel.call(prompt);
        String text = call.getResult().getOutput().getText();
        return removeThinkTag(text);
    }

    private String removeThinkTag(String text) {
        if (StrUtil.isNotBlank(text) && text.contains("<think>") && text.contains("</think>")) {
            text = text.replaceAll("(?s)<think>.*?</think>", "").trim();
        }
        text = StrUtil.trim(text);
        if (text.startsWith("\"") && text.endsWith("\"")) {
            text = text.substring(1, text.length() - 1).trim();
        }
        return text;
    }
}
